package server;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

import entry.Entry;
import event.Event;
import event.EventHandler;

public class SearchEventHandler implements EventHandler {

	public static final int BUFFER_SIZE = 4096;

	@Override
	public void handle(Event e) {
		if (e.type == Event.SEARCH_TYPE) {
			String[] query = e.parameters.split("DELIMETER");

			if (query.length == 2) {

				Model model = Model.getInstance();
				ArrayList<Entry> list = model.search(query[0], query[1]);

				try {
					sendSearchResult(query[0], list, e.getOutputStream());
				} catch (IOException e1) {
					System.out.println("> Unable to send result to client");
				}
			}
		}
	}

	private void sendSearchResult(String query, ArrayList<Entry> result,
			DataOutputStream os) throws IOException {
		/*
		 * Send the header.
		 */
		os.writeInt(Event.DIR_TYPE);
		os.writeLong(0);
		os.writeLong(0);

		ByteArrayOutputStream bos = new ByteArrayOutputStream();

		ObjectOutputStream aos = new ObjectOutputStream(bos);
		aos.writeObject(result);

		os.writeInt(bos.size());
		os.writeUTF(query);

		bos.writeTo(os);

		bos.close();
		aos.close();
	}

}
